package com.king.base;

import com.google.common.base.Throwables;

    /**
     * Created by Administrator on 2015/4/24.
     */
    public class ThrowablesDemo {
         public static void main(String[] args) {
          ThrowablesDemo tester = new ThrowablesDemo();

             try {
                tester.showcaseThrowables();

            } catch (InvalidInputException e) {
                System.out.println(Throwables.getRootCause(e));
            }catch (Exception e) {

               System.out.println(Throwables.getStackTraceAsString(e));
            }
/*
            try {
                tester.showcaseThrowables1();
            }catch (Exception e) {
                System.out.println(Throwables.getStackTraceAsString(e));
            }*/
        }

        public   void showcaseThrowables() throws InvalidInputException{
            try {
                sqrt(-3.0);
            } catch (Throwable e) {

                Throwables.propagateIfInstanceOf(e, InvalidInputException.class);
                //如果Throwable是Error或RuntimeException，直接抛出；否则把Throwable包装成RuntimeException抛出
                Throwables.propagate(e);
            }
        }

        public void showcaseThrowables1(){
            try {
                int[] data = {1,2,3};
                getValue(data, 4);
            } catch (Throwable e) {
                Throwables.propagateIfInstanceOf(e, IndexOutOfBoundsException.class);
                Throwables.propagate(e);
            }
        }

        public double sqrt(double input) throws InvalidInputException{
            if(input < 0) throw new InvalidInputException();
            return Math.sqrt(input);
        }

        public double getValue(int[] list, int index) throws IndexOutOfBoundsException {
            return list[index];
        }


    }

    class InvalidInputException extends Exception {
    }



